package de.baumann.browser.adapter;

import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;


import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import de.baumann.browser.R;
import de.baumann.browser.utils.Constants;
import de.baumann.browser.web.WindowUiController;


public class HomeWebsiteAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    Map<String, String> mData;
    List<String> keys = new ArrayList<>();
    Context mContext;
    @Deprecated
    WindowUiController mController;

    private OnWebsiteClickListener websiteClickListener;

    public HomeWebsiteAdapter(Context context, Map<String, String> data) {
        mContext = context;
        mData = data;
        keys.addAll(mData.keySet());
    }

    @Deprecated
    public void setUiController(WindowUiController uiController) {
        this.mController = uiController;
    }

    public void setWebsiteClickListener(OnWebsiteClickListener websiteClickListener) {
        this.websiteClickListener = websiteClickListener;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        return new WebsiteViewHolder(LayoutInflater.from(mContext).inflate(R.layout.layout_uc_website_item, null));
    }

    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        WebsiteViewHolder viewHolder = (WebsiteViewHolder) holder;
        final String website = keys.get(position);
        viewHolder.website.setText(website);
        Drawable icon = mContext.getDrawable(Constants.WEBSITE_ICON_RES[position]);
        icon.setBounds(new Rect(0, 0, icon.getIntrinsicWidth(), icon.getIntrinsicHeight()));
        viewHolder.website.setCompoundDrawables(null, icon, null, null);
        viewHolder.website.setOnClickListener(v -> {

            if (websiteClickListener!=null){
                websiteClickListener.onWebstieClick(mData.get(website));
            }

//            if (mController != null) {
//                mController.load(mData.get(website));
//            }
        });
    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    private static class WebsiteViewHolder extends RecyclerView.ViewHolder {
        TextView website;

        WebsiteViewHolder(View view) {
            super(view);
            website = view.findViewById(R.id.tvHomeWebsiteItem);
        }
    }

    public interface OnWebsiteClickListener{
        void onWebstieClick(String url);
    }
}
